package com.zhitong.money.services;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zhitong.money.entity.Employee;
import com.zhitong.money.entity.Position;
import com.zhitong.money.exception.AddException;
import com.zhitong.money.exception.DeleteException;
import com.zhitong.money.exception.RepeatException;
import com.zhitong.money.exception.UpdateException;
import com.zhitong.money.mapper.EmployeeMapper;
import com.zhitong.money.mapper.PositionMapper;
import com.zhitong.money.services.api.IEmployeeService;
import com.zhitong.money.services.api.IUserService;
import com.zhitong.money.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Slf4j
@Service
public class EmployeeService implements IEmployeeService {
    @Autowired
    private EmployeeMapper mapper;

    @Autowired
    private IUserService userService;

    @Autowired
    private PositionMapper positionMapper;

    @Override
    public List<Employee> findAllEmployee() throws Exception {
        List<Employee> employees = mapper.findAllEmployee();
        if (employees==null||employees.isEmpty()){
            log.info("员工查询位0");
            throw new NullPointerException("findAllEmployee:暂无员工可查询");
        }
        return employees;
    }

    @Override
    public PageInfo findEmployeeByPage(Map<String,Object> map) throws Exception {

        int pageNum=map.containsKey("pageNum")?(int)map.get("pageNum"):1;
        int pageSize=map.containsKey("pageSize")?(int)map.get("pageSize"):5;
        PageHelper.startPage(pageNum,pageSize);
        List<Employee> employees = mapper.findEmployeeByMap(map);
        if (employees==null||employees.isEmpty()){
            log.info("员工查询位0");
            throw new NullPointerException("暂无数据可查询");
        }
        PageInfo pageInfo=new PageInfo(employees);
        return pageInfo;
    }

    @Override
    public List<Employee> findEmployeeByMap(Map<String, Object> map) throws Exception {
        List<Employee> employeeByMap = mapper.findEmployeeByMap(map);
        if (employeeByMap ==null || employeeByMap.isEmpty()){
            throw new NullPointerException("findEmployeeByMap:查询为空");
        }
        return employeeByMap;
    }

    @Override
    public Employee findEmployeeById(String id) throws Exception {
        Employee employeeById = mapper.findEmployeeById(id);
        if (employeeById==null){
            throw new NullPointerException();
        }
        return employeeById;
    }

    @Override
    public List<Employee> findSuperior(String pid) throws Exception {
        Position positionById = positionMapper.findPositionById(pid);
        if (positionById==null){
           throw new NullPointerException("findSuperior:查询为空");
        }
        //如果是经理级别以下的,需要查询同部门下的上级
        if (!positionById.getLeaderId().equals("01")){
            List<Employee> employeeByPid = mapper.findEmployeeByPid(positionById.getLeaderId());
            return employeeByPid;
        }else {
            return null;
        }


    }

    @Override
    public List<String> findIdsByPid(String pid) throws Exception {
        List<String> idsByPid = mapper.findIdsByPid(pid);
        if (idsByPid==null){
            throw new NullPointerException();
        }
        return idsByPid;
    }

    @Override
    public Employee findEmployeeByTellerId(String tellerId) throws Exception {
        Employee employee=mapper.findEmployeeByTellerId(tellerId);
        if (employee==null){
            throw new NullPointerException("findEmployeeByTellerId:查询为空");
        }
        return employee;
    }

    @Override
    public List<Employee> findEmployeeByTids(List<String> tids) throws Exception {
        List<Employee> employeeByTids = mapper.findEmployeeByTids(tids);
        if (employeeByTids==null || employeeByTids.isEmpty()){
            throw new NullPointerException("findEmployeeByTids:查询为空");
        }
        return employeeByTids;
    }

    @Override
    public Employee findEmployeeByIdCard(String idCard) throws Exception {
        Employee employee=mapper.findEmployeeByIdCard(idCard);
        if (employee==null){
            throw new NullPointerException();
        }
        return employee;
    }

    @Transactional
    @Override
    public void addEmployee(Employee employee) throws Exception {
        try {
            //唯一性验证
            Employee employeeByIdCard = mapper.findEmployeeByIdCard(employee.getIdCard());
            if (employeeByIdCard!=null){
                throw new RepeatException();
            }
            //生成员工号
            employee.setTellerId(generateTid());
            //
            employee.setUStatus("00");
            //可添加员工登录账号功能
            mapper.addEmployee(employee);
        } catch (Exception e) {
            if (e instanceof RepeatException){
                throw e;
            }else {
                throw new AddException("addEmployee员工添加失败:"+e.getMessage());
            }
        }
    }

    @Transactional
    @Override
    public void updateEmployee(Employee employee) throws Exception {
        try {
            //判断更改后是否唯一

            mapper.updateEmployee(employee);
        } catch (Exception e) {
            throw new UpdateException("updateEmployee员工更新失败:"+e.getMessage());
        }
    }

    @Transactional
    @Override
    public void updatePidByIds(List<String> ids, String pid) {
        try {
            mapper.updatePidByIds(ids,pid);
        } catch (Exception e) {
            throw new UpdateException("updateEStatusByIds:更新失败!"+e.getMessage());
        }
    }

    @Transactional
    @Override
    public void delEmployee(String id) throws Exception {
        try {
            //删除员工时,需要删除其用户账号
            Employee employeeById = mapper.findEmployeeById(id);
            userService.delUserByTid(employeeById.getTellerId());
            //删除请假信息

            //删除信息


            //删除员工
            mapper.delEmployee(id);
        } catch (Exception e) {
            throw new DeleteException("delEmployee员工删除失败:"+e.getMessage());
        }
    }

    @Transactional
    @Override
    public void delEmployeeByIds(Map<String,Object> map) throws Exception {
        try {
            List<String> ids= (List<String>) map.get("delList");
            List<String> tids = (List<String>) map.get("delTids");
            //需要删除其用户账号
            userService.delUserByTids(tids);

            //删除请假信息

            //删除信息

            mapper.delEmployeeByIds(ids);
        } catch (Exception e) {
            throw new DeleteException("delEmployeesByIds:删除失败"+e.getMessage());
        }
    }

    /**
    * @description 生成员工号
    * @author: Andy Zhang
    * @date: 2021/1/26 21:44
    * @param:
    * @return:
    */
    private String generateTid(){
        StringBuffer tid=new StringBuffer("XY");
        Random random=new Random();
        int endNum=random.nextInt(900)+100;
        String time= DateUtil.dateToStr(new Date(),DateUtil.FORMAT_DATE_TID);
       String tellerId = tid.append(time).append(endNum).toString();
        Employee employeeByTellerId = mapper.findEmployeeByTellerId(tellerId);
        if (employeeByTellerId==null) {
            return tellerId;
        }else{
            return generateTid();
        }
    }
}
